package com.zpkj.portal.third.jpush;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.ClientConfig;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification;

/**
 * 极光推送 工具类
 * @author xc
 */
public class JPushPushUtils {
    protected static final Logger LOG = LoggerFactory.getLogger(JPushPushUtils.class);
    //极光平台配置的appKey
	private static final String appKey = "2550849cefa15cca96e46b61";
	//极光平台配置的masterSecret
	private static final String masterSecret = "70baf120d892f60b13b560ab";
	
	//所有平台 按标签发送
	public static boolean buildPushAll(String content,String tagName) throws APIConnectionException, APIRequestException  {
    	ClientConfig config = ClientConfig.getInstance();
    	config.setTimeToLive(0);
    	JPushClient jpushClient = new JPushClient(masterSecret, appKey, null , config);
    	PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.tag(tagName))
                .setNotification(Notification.alert(content))
                .build();
    	PushResult result = jpushClient.sendPush(payload);
    	return result.isResultOK();
    }
	
	@SuppressWarnings("deprecation")
	public static void sendToAll(String content) {
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);
        PushPayload payload = buildPushObject_all_all_alert(content);
        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
	}
	
	/**
	 * 根据别名发消息推送
	 * @param alias   别名
	 * @param content 消息内容
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static Map<String,Object> sendToOneUser(String alias,String content){
		JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);
		PushPayload payload = pushMessToAlias(content, alias);
		try {
			PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);
		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);
			e.printStackTrace();
		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
			e.printStackTrace();
		}
//		JsonElement je = pp.toJSON();
//		Gson gson = new Gson();
	    Map<String, Object> map = new HashMap<String, Object>();
//	    map = gson.fromJson(je.toString(), map.getClass());
	    return map;
	}
	
	//发所有人，广播
	public static PushPayload buildPushObject_all_all_alert(String content) {
	    return PushPayload.alertAll(content);
	}
	
	//按别名推送 所有平台，推送目标是别名为 "alias1"，通知内容为 ALERT。
    public static PushPayload pushMessToAlias(String content,String alias) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.alert(content))
                .build();
    }
    
    //平台是 Android，目标是 tag 为 "tag1" 的设备，内容是 Android 通知 ALERT，并且标题为 TITLE。
    public static PushPayload buildPushObject_android_tag_alertWithTitle(String content,String alias,String tag,String title) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.tag(tag))
                .setNotification(Notification.android(content, title, null))
                .build();
    }
    
    /**
     * 按照注册id推送
     * @param content
     * @param alias
     * @param tag
     * @param title
     * @return
     */
    public static PushPayload buildPushOne_android(String content,String alias,String tag,String title) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
//                .setAudience(Audience.tag(tag))
//                .setAudience(Audience.registrationId(registrationId))
                .setNotification(Notification.android(content, title, null))
                .build();
    }
    
//    public static PushPayload buildPushObject_android_and_ios() {
//        return PushPayload.newBuilder()
//                .setPlatform(Platform.android_ios())
//                .setAudience(Audience.tag("tag1"))
//                .setNotification(Notification.newBuilder()
//                		.setAlert("alert content")
//                		.addPlatformNotification(AndroidNotification.newBuilder()
//                				.setTitle("Android Title").build())
//                		.addPlatformNotification(IosNotification.newBuilder()
//                				.incrBadge(1)
//                				.addExtra("extra_key", "extra_value").build())
//                		.build())
//                .build();
//    }
//    
//    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
//        return PushPayload.newBuilder()
//                .setPlatform(Platform.ios())
//                .setAudience(Audience.tag_and("tag1", "tag_all"))
//                .setNotification(Notification.newBuilder()
//                        .addPlatformNotification(IosNotification.newBuilder()
//                                .setAlert(ALERT)
//                                .setBadge(5)
//                                .setSound("happy")
//                                .addExtra("from", "JPush")
//                                .build())
//                        .build())
//                 .setMessage(Message.content(MSG_CONTENT))
//                 .setOptions(Options.newBuilder()
//                         .setApnsProduction(true)
//                         .build())
//                 .build();
//    }
    
    /**
     * 对某个标签组发送消息
     * @return
     */
    public static PushPayload pushMessToOneTag(String tagName,String content) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag(tagName))
//                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(content)
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }
    
    //平台是 Andorid 与 iOS，推送目标是 （"tag1" 与 "tag2" 的并集）且（"alias1" 与 "alias2" 的并集），推送内容是 - 内容为 MSG_CONTENT 的消息，并且附加字段 from = JPush。
//    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
//        return PushPayload.newBuilder()
//                .setPlatform(Platform.android_ios())
//                .setAudience(Audience.newBuilder()
//                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
//                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
//                        .build())
//                .setMessage(Message.newBuilder()
//                        .setMsgContent(MSG_CONTENT)
//                        .addExtra("from", "JPush")
//                        .build())
//                .build();
//    }

//    public static void testSendPushWithCustomConfig() {
//        ClientConfig config = ClientConfig.getInstance();
//        // Setup the custom hostname
//        config.setPushHostName("https://api.jpush.cn");
//
//        JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3, null, config);
//
//        // For push, all you need do is to build PushPayload object.
//        PushPayload payload = buildPushObject_all_all_alert();
//
//        try {
//            PushResult result = jpushClient.sendPush(payload);
//            LOG.info("Got result - " + result);
//
//        } catch (APIConnectionException e) {
//            LOG.error("Connection error. Should retry later. ", e);
//
//        } catch (APIRequestException e) {
//            LOG.error("Error response from JPush server. Should review and fix it. ", e);
//            LOG.info("HTTP Status: " + e.getStatus());
//            LOG.info("Error Code: " + e.getErrorCode());
//            LOG.info("Error Message: " + e.getErrorMessage());
//            LOG.info("Msg ID: " + e.getMsgId());
//        }
//    }
//
//    public static void testSendIosAlert() {
//        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
//
//        IosAlert alert = IosAlert.newBuilder()
//                .setTitleAndBody("test alert", "test ios alert json")
//                .setActionLocKey("PLAY")
//                .build();
//        try {
//            PushResult result = jpushClient.sendIosNotificationWithAlias(alert, new HashMap<String, String>(), "alias1");
//            LOG.info("Got result - " + result);
//        } catch (APIConnectionException e) {
//            LOG.error("Connection error. Should retry later. ", e);
//        } catch (APIRequestException e) {
//            LOG.error("Error response from JPush server. Should review and fix it. ", e);
//            LOG.info("HTTP Status: " + e.getStatus());
//            LOG.info("Error Code: " + e.getErrorCode());
//            LOG.info("Error Message: " + e.getErrorMessage());
//        }
//    }
//
//    public static void testSendWithSMS() {
//        JPushClient jpushClient = new JPushClient(masterSecret, appKey);
//        try {
//            SMS sms = SMS.content("Test SMS", 10);
//            PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
//            LOG.info("Got result - " + result);
//        } catch (APIConnectionException e) {
//            LOG.error("Connection error. Should retry later. ", e);
//        } catch (APIRequestException e) {
//            LOG.error("Error response from JPush server. Should review and fix it. ", e);
//            LOG.info("HTTP Status: " + e.getStatus());
//            LOG.info("Error Code: " + e.getErrorCode());
//            LOG.info("Error Message: " + e.getErrorMessage());
//        }
//    }

}